package com.qf.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author 千锋健哥
 */
@Component
public class AuthFilter implements Ordered, GlobalFilter {

    /**
     * 编写过滤器业务
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        //1. 获取用户请求中的权限参数
        String token = exchange.getRequest().getQueryParams().getFirst("token");

        //2. 如果没有抛出401权限不足异常
        if (StringUtils.isEmpty(token)) {
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }

        //3. 如果有放行
        return chain.filter(exchange);
    }

    /**
     * 如果有多个过滤器, 这里定义执行顺序
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }

}
